package org.example.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.example.model.Questionnaire;
import org.example.model.UserResponse;
import org.example.service.QuestionnaireService;
import org.example.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*") // 允许跨域请求，生产环境中应该限制来源
@Api(tags = "问卷管理", description = "问卷创建、查询和回答相关接口")
public class QuestionnaireController {

    @Autowired
    private QuestionnaireService questionnaireService;
    
    @Autowired
    private FileUploadUtil fileUploadUtil;

    // 创建问卷
    @PostMapping("/questionnaires")
    @ApiOperation(value = "创建问卷", notes = "创建一个新的问卷，包含问题和选项")
    public ResponseEntity<Object> createQuestionnaire(
            @ApiParam(value = "问卷信息", required = true) @RequestBody Questionnaire questionnaire) {
        Questionnaire savedQuestionnaire = questionnaireService.createQuestionnaire(questionnaire);
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("code", 1);
        result.put("data", savedQuestionnaire);
        result.put("msg", "创建成功");
        return ResponseEntity.ok(result);
    }

    // 获取所有问卷
    @GetMapping("/questionnaires")
    @ApiOperation(value = "获取所有问卷", notes = "获取系统中所有活跃的问卷列表")
    public ResponseEntity<Object> getAllQuestionnaires() {
        List<Questionnaire> questionnaires = questionnaireService.getAllQuestionnaires();
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("code", 1);
        result.put("data", questionnaires);
        result.put("msg", "获取成功");
        return ResponseEntity.ok(result);
    }

    // 获取单个问卷
    @GetMapping("/questionnaires/{id}")
    @ApiOperation(value = "获取问卷详情", notes = "根据问卷ID获取问卷详细信息，包含所有问题和选项")
    public ResponseEntity<Object> getQuestionnaireById(
            @ApiParam(value = "问卷ID", required = true) @PathVariable Long id) {
        Questionnaire questionnaire = questionnaireService.getQuestionnaireById(id);
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("code", 1);
        result.put("data", questionnaire);
        result.put("msg", "获取成功");
        return ResponseEntity.ok(result);
    }
    
    // 更新问卷
    @PutMapping("/questionnaires/{id}")
    @ApiOperation(value = "更新问卷", notes = "更新现有问卷的信息，包括问题和选项")
    public ResponseEntity<Object> updateQuestionnaire(
            @ApiParam(value = "问卷ID", required = true) @PathVariable Long id,
            @ApiParam(value = "问卷信息", required = true) @RequestBody Questionnaire questionnaire) {
        if (!id.equals(questionnaire.getId())) {
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("code", 0);
            result.put("data", null);
            result.put("msg", "ID不一致");
            return ResponseEntity.badRequest().body(result);
        }
        Questionnaire updatedQuestionnaire = questionnaireService.updateQuestionnaire(questionnaire);
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("code", 1);
        result.put("data", updatedQuestionnaire);
        result.put("msg", "更新成功");
        return ResponseEntity.ok(result);
    }

    // 提交问卷回答
    @PostMapping("/user-responses")
    @ApiOperation(value = "提交问卷回答", notes = "用户提交问卷的回答内容")
    public ResponseEntity<Object> submitResponse(
            @ApiParam(value = "用户回答信息", required = true) @RequestBody UserResponse userResponse) {
        UserResponse savedResponse = questionnaireService.saveUserResponse(userResponse);
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("code", 1);
        result.put("data", savedResponse);
        result.put("msg", "提交成功");
        return ResponseEntity.ok(result);
    }

    // 获取用户的所有回答
    @GetMapping("/user-responses/{userId}")
    @ApiOperation(value = "获取用户回答", notes = "获取指定用户的所有问卷回答")
    public ResponseEntity<Object> getUserResponses(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId) {
        List<UserResponse> responses = questionnaireService.getUserResponses(userId);
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("code", 1);
        result.put("data", responses);
        result.put("msg", "获取成功");
        return ResponseEntity.ok(result);
    }
    
    // 删除问卷接口
    @DeleteMapping("/questionnaires/{id}")
    @ApiOperation(value = "删除问卷", notes = "根据问卷ID删除问卷及其关联的问题和选项")
    public ResponseEntity<Object> deleteQuestionnaire(
            @ApiParam(value = "问卷ID", required = true) @PathVariable Long id) {
        try {
            questionnaireService.deleteQuestionnaire(id);
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("code", 1);
            result.put("data", null);
            result.put("msg", "删除成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("code", 0);
            result.put("data", null);
            result.put("msg", "服务器错误");
            return ResponseEntity.status(500).body(result);
        }
    }

    // 问题图片上传接口
    @PostMapping("/questionnaires/upload-image")
    @ApiOperation(value = "上传问题图片", notes = "上传单个问题图片，返回图片URL")
    public ResponseEntity<Object> uploadQuestionImage(@RequestParam("file") MultipartFile file) {
        try {
            String url = fileUploadUtil.uploadQuestionImage(file);
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("code", 1);
            result.put("data", url);
            result.put("msg", "上传成功");
            return ResponseEntity.ok(result);
        } catch (IllegalArgumentException e) {
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("code", 0);
            result.put("data", null);
            result.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            e.printStackTrace();
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("code", 0);
            result.put("data", null);
            result.put("msg", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
}